package cn.xc.basic.service.impl;

import cn.xc.basic.constant.VerifyCodeConstant;
import cn.xc.basic.domain.SmsCodeDto;
import cn.xc.basic.service.IVerifyCodeService;
import cn.xc.basic.util.SmsUtils;
import cn.xc.basic.util.StrUtils;
import cn.xc.basic.util.VerifyCodeUtils;
import cn.xc.org.exception.BusinessException;
import cn.xc.user.domain.User;
import cn.xc.user.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private UserMapper userMapper;

    @Override
    public String imageVerifyCode(String key) {
        String code = VerifyCodeUtils.generateVerifyCode(4);
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
        return VerifyCodeUtils.verifyCode(110, 40, code);
    }

    @Override
    public void smsCode(SmsCodeDto smsCodeDto) {
        String phone = smsCodeDto.getPhone();
        String imageCode = smsCodeDto.getImageCode();
        String imageCodeKey = smsCodeDto.getImageCodeKey();

        //校验手机号，图片验证码，
        if (StringUtils.isEmpty(phone)) {
            throw new BusinessException("手機號不能為空哦!");
        }
        if (StringUtils.isEmpty(imageCode)) {
            throw new BusinessException("圖片驗證碼不能為空哦!");
        }
        if (StringUtils.isEmpty(imageCodeKey)) {
            throw new BusinessException("請重新獲取圖片驗證碼!");
        }

        //b.验证手机号码是否注册过
        User user = userMapper.loadByPhone(phone);
        if (user != null){
            throw new BusinessException("该手机号已被注册!!");
        }

        Object imageObj = redisTemplate.opsForValue().get(imageCodeKey);
        if (imageObj == null){
            throw new BusinessException("图片验证码已过期!");
        }
        if (!imageObj.toString().equalsIgnoreCase(imageCode)){
            throw new BusinessException("图片验证码错误!");
        }

        Object smsObj = redisTemplate.opsForValue().get(VerifyCodeConstant.REGISTER_CODE_PREFIX + phone);
        String smsCode = null;
        if (smsObj == null) {
            smsCode = StrUtils.getRandomString(6);
        } else {
            long nowTime = System.currentTimeMillis();
            String oldTimeTemp = smsObj.toString().split(":")[1];
            long oldTime = Long.parseLong(oldTimeTemp);
            if (nowTime - oldTime < 1 * 60 * 1000) {
                throw new BusinessException("請勿重複提交信息!!");
            } else {
                smsCode = smsObj.toString().split(":")[0];
            }
        }
        //将验证码数据添加到redis
        redisTemplate.opsForValue().set(VerifyCodeConstant.REGISTER_CODE_PREFIX + phone,
                smsCode + ":" + System.currentTimeMillis(),3, TimeUnit.MINUTES);//存3分钟
        System.out.println("你的验证码是：" + smsCode+",请在3分钟内使用!!!");
    }

    /**
     * 微信掃碼手機驗證碼
     * @param smsCodeDto
     */
    @Override
    public void binderSmsCode(SmsCodeDto smsCodeDto) {
        String phone = smsCodeDto.getPhone();

        //校验手机号，图片验证码，
        if (StringUtils.isEmpty(phone)) {
            throw new BusinessException("手機號不能為空哦!");
        }

        Object smsObj = redisTemplate.opsForValue().get(VerifyCodeConstant.BINDER_CODE_PREFIX + phone);
        String smsCode = null;
        if (smsObj == null) {
            smsCode = StrUtils.getRandomString(6);
        } else {
            long nowTime = System.currentTimeMillis();
            String oldTimeTemp = smsObj.toString().split(":")[1];
            long oldTime = Long.parseLong(oldTimeTemp);
            if (nowTime - oldTime < 1 * 60 * 1000) {
                throw new BusinessException("請勿重複提交信息!!");
            } else {
                smsCode = smsObj.toString().split(":")[0];
            }
        }
        //将验证码数据添加到redis
        redisTemplate.opsForValue().set(VerifyCodeConstant.BINDER_CODE_PREFIX + phone,
                smsCode + ":" + System.currentTimeMillis(),3, TimeUnit.MINUTES);//存3分钟
        System.out.println("你的验证码是：" + smsCode+",请在3分钟内使用!!!");
    }


//    @PostMapping("/email")
//    public void auditPass() throws MessagingException {
//        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
//        messageHelper.setFrom("3206009761@qq.com");
//        messageHelper.setSubject("烏拉!!!");
//        messageHelper.setText("<h1>郵件註冊</h1><br><a href='" +
//                "http://localhost:8080/verifyCode/email/'>點擊鏈接激活店鋪</a>", true);
//        messageHelper.setTo("3206009761@qq.com");
//        javaMailSender.send(mimeMessage);
//   }
}
